package com.example.petshopping.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import com.example.petshopping.PetShoppingApplication;
import com.example.petshopping.R;
import com.example.petshopping.config.AppConfig;
import com.example.petshopping.model.AppAuthLoginRespVO;
import com.example.petshopping.model.CommonResult;
import com.example.petshopping.model.SocialLoginRequest;
import com.example.petshopping.network.RetrofitClient;
import com.example.petshopping.ui.main.MainActivity;
import com.example.petshopping.utils.TokenManager;

// 使用全限定类名替换导入
// import com.tencent.mm.opensdk.modelbase.BaseReq;
// import com.tencent.mm.opensdk.modelbase.BaseResp;
// import com.tencent.mm.opensdk.modelmsg.SendAuth;
// import com.tencent.mm.opensdk.openapi.IWXAPI;
// import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 处理微信登录回调的Activity
 */
public class WXEntryActivity extends Activity implements com.tencent.mm.opensdk.openapi.IWXAPIEventHandler {

    private com.tencent.mm.opensdk.openapi.IWXAPI api;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // 获取微信API对象
        api = PetShoppingApplication.getWXApi();
        if (api != null) {
            api.handleIntent(getIntent(), this);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        if (api != null) {
            api.handleIntent(intent, this);
        }
    }

    // 微信发送请求到第三方应用时，会回调此方法
    @Override
    public void onReq(com.tencent.mm.opensdk.modelbase.BaseReq baseReq) {
        // 处理微信请求，这里一般不需要处理
    }

    // 第三方应用发送到微信的请求处理后的响应结果，会回调此方法
    @Override
    public void onResp(com.tencent.mm.opensdk.modelbase.BaseResp resp) {
        if (resp instanceof com.tencent.mm.opensdk.modelmsg.SendAuth.Resp) {
            com.tencent.mm.opensdk.modelmsg.SendAuth.Resp authResp = (com.tencent.mm.opensdk.modelmsg.SendAuth.Resp) resp;
            
            switch (resp.errCode) {
                case com.tencent.mm.opensdk.modelbase.BaseResp.ErrCode.ERR_OK:
                    // 用户同意
                    String code = authResp.code;
                    String state = authResp.state;
                    // 处理微信登录逻辑
                    handleWechatLogin(code, state);
                    break;
                    
                case com.tencent.mm.opensdk.modelbase.BaseResp.ErrCode.ERR_USER_CANCEL:
                    // 用户取消
                    Toast.makeText(this, "登录取消", Toast.LENGTH_SHORT).show();
                    finish();
                    break;
                    
                case com.tencent.mm.opensdk.modelbase.BaseResp.ErrCode.ERR_AUTH_DENIED:
                    // 用户拒绝授权
                    Toast.makeText(this, "授权被拒绝", Toast.LENGTH_SHORT).show();
                    finish();
                    break;
                    
                default:
                    // 其他错误
                    Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show();
                    finish();
                    break;
            }
        }
    }

    /**
     * 处理微信登录
     */
    private void handleWechatLogin(String code, String state) {
        // 构建请求参数
        SocialLoginRequest request = new SocialLoginRequest(
                AppConfig.WECHAT_OPEN_TYPE, // 微信开放平台类型
                code,
                state
        );
        
        // 发起网络请求
        RetrofitClient.getInstance().getApiService().socialLogin(request)
                .enqueue(new Callback<CommonResult<AppAuthLoginRespVO>>() {
                    @Override
                    public void onResponse(Call<CommonResult<AppAuthLoginRespVO>> call, Response<CommonResult<AppAuthLoginRespVO>> response) {
                        if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                            // 登录成功，保存token等信息
                            AppAuthLoginRespVO loginResp = response.body().getData();
                            if (loginResp != null) {
                                // 保存token到本地
                                TokenManager.saveToken(WXEntryActivity.this, loginResp.getAccessToken());
                                TokenManager.saveUserId(WXEntryActivity.this, loginResp.getUserId());
                                
                                // 跳转到主页
                                Intent intent = new Intent(WXEntryActivity.this, MainActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                startActivity(intent);
                                finish();
                            } else {
                                Toast.makeText(WXEntryActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                                finish();
                            }
                        } else {
                            // 登录失败
                            String errorMsg = "登录失败";
                            if (response.body() != null) {
                                errorMsg = response.body().getMsg();
                            }
                            Toast.makeText(WXEntryActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
                            finish();
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult<AppAuthLoginRespVO>> call, Throwable t) {
                        // 网络请求失败
                        Toast.makeText(WXEntryActivity.this, "网络请求失败", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                });
    }
} 